import hashlib
import json
import re
import logging
import urllib
from urllib.parse import urlencode
import requests
from django.core.paginator import Paginator
from django.http import JsonResponse
from lapi_app.models.environment_model.environment import Environment
from lapi_app.models.testcase_model.testcase import Parametric, Testcase, Parametric_result
from lapi_app.models.user_model.user_info import Userinfo
from lapi_app.view.testcase_view.updateJson import updateJsonValue

logger = logging.getLogger('django')


def batch_send(request):
    global assert_result, assert_status, res, assert_res_data, param, body_res, times, status, a_status
    body_data = request.body
    if not body_data:
        return JsonResponse({
            "code": 100,
            "message": "参数异常"
        })
    data = json.loads(body_data)
    user_id = data["user_id"]
    t_id = data["testcase_id"]
    url = data["url"]
    body_type = data["body_type"]
    t_method = data["method"]
    t_headers = data["headers"]
    api_type = data["api_type"]
    t_params = data["params"]
    if Parametric_result.objects.filter(p_testcase_id=t_id).count() >= 1:
        Parametric_result.objects.filter(p_testcase_id=t_id).delete()
    else:
        pass
    cases = Testcase.objects.filter(id=t_id)
    for case in cases:
        req_url = case.t_environment.e_address + case.t_url
    params_data = []
    params_result = []
    if Parametric.objects.filter(p_testcase_id=t_id, parametric_type=1).count() > 0:
        params = {}
        if t_params:
            for item in t_params:
                params[item['key']] = item['value']
        paramss = Parametric.objects.get(p_testcase_id=t_id, parametric_type=1)
        params_value = paramss.file_content.replace("'", '"')
        for i in eval(params_value):
            t_params = data["params"]
            if "${" in json.dumps(t_params) and "}" in json.dumps(t_params):
                key = re.findall(r"\${(.+?)}", json.dumps(t_params))
                for b in range(len(key)):
                    b_key = "${" + key[b] + "}"
                    if key[b] in i:
                        variable = i[key[b]]
                        t_params = json.dumps(t_params).replace(b_key, variable)
                        t_params = json.loads(t_params)
            params_data.append(t_params)
        for j in params_data:
            param_list = []
            for m in j:
                for key, value in m.items():
                    param_dict = {m["key"]: m["value"]}
                param_list.append(param_dict)
            params_result.append(param_list)

    else:
        params_data = []
    if t_headers is not None:
        headers = t_headers
    else:
        headers = {}
    body = data["body"]
    if data["body"] == '' or data["body"] == {}:
        payload = {}
    else:
        payload_data = []
        if Parametric.objects.filter(p_testcase_id=t_id, parametric_type=2).count() > 0:
            b = Parametric.objects.get(p_testcase_id=t_id, parametric_type=2)
            body_value = b.file_content.replace("'", '"')
            for i in eval(body_value):
                body = data["body"]
                if "${" in json.dumps(body) and "}" in json.dumps(body):
                    key = re.findall(r"\${(.+?)}", json.dumps(body))
                    for b in range(len(key)):
                        b_key = "${" + key[b] + "}"
                        if key[b] in i:
                            variable = i[key[b]]
                            body = json.dumps(body).replace(b_key, str(variable))
                            body = json.loads(body)
                payload_data.append(body)
        else:
            payload_data = []
    assert_list = []
    if Parametric.objects.filter(p_testcase_id=t_id, parametric_type=3).count() > 0:
        parametric_assert = Parametric.objects.filter(p_testcase_id=t_id, parametric_type=3)
        for a in parametric_assert:
            assert_data = json.loads(a.file_content.replace("'", '"'))

        for j in assert_data:
            assert_result = []
            for key, value in j.items():
                assert_dict = {}
                assert_dict["assert_key"] = key
                assert_dict["assert_value"] = value
                assert_result.append(assert_dict)
            assert_list.append(assert_result)
    else:
        assert_data = []
    result_list = []
    if payload_data:
        for i in range(len(payload_data)):
            if params_result:
                params = params_result[i]
            else:
                params = []
            if assert_list:
                assert_r = assert_list[i]
            else:
                assert_r = []
            case_dict = {
                "url": req_url,
                "body": payload_data[i],
                "method": t_method,
                "params": params,
                "assert": assert_r,
                "headers": headers,
                "api_type": api_type,
                "body_type": body_type
            }
            result_list.append(case_dict)
    p_list = []
    for i in result_list:
        if i["api_type"] == 1:
            # 普通接口
            pass
        elif i["api_type"] == 2:
            # 海外SDK(测试环境+预发布+生产环境)
            jwt_key = "2895d9ad485692b52c1ecef7d5f28300"  # 参数管理字段: pay_sign(100000151-纵剑仙界)
            new_payload = {}
            for key in sorted(i["body"].keys()):
                if key != "clicks" and not i["body"][key]:
                    new_payload[key] = "{}"
                else:
                    new_payload[key] = json.dumps(i["body"][key], separators=(',', ':'), ensure_ascii=False)
            pay_load = urllib.parse.unquote(urlencode(new_payload).replace("+", " "))
            pay_load = pay_load.replace("'", '"')
            md5_data = pay_load + "&" + jwt_key
            md = hashlib.md5()
            md.update(md5_data.encode("utf-8"))
            md_result = md.hexdigest()
            logger.info("md5的结果 =" + str(md_result))
            i["body"].update({"sign": md_result})
        elif i["api_type"] == 8:
            # 研发二验获取token
            jwt_key = "91e64e9a1b3e3208d86b91980affe013"  # 参数管理字段: pay_sign(100000151-纵剑仙界)
            new_payload = {}
            i["body"].update({"jh_sign": jwt_key})
            for key in sorted(i["body"].keys()):
                if key != "clicks" and not i["body"][key]:
                    new_payload[key] = "{}"
                else:
                    new_payload[key] = json.dumps(i["body"][key], separators=(',', ':'), ensure_ascii=False)
            pay_loads = urllib.parse.unquote(urlencode(new_payload).replace("+", ""))
            pay_loades = pay_loads.replace('"', '')
            md5_data = pay_loades
            md = hashlib.md5()
            md.update(md5_data.encode("utf-8"))
            md_result = md.hexdigest()
            logger.info("md5的结果 =" + str(md_result))
            i["body"].update({"sign": md_result})
            payload = json.loads(json.dumps(i["body"]))
        elif i["api_type"] == 9:
            # 国内SDK二验（生产环境）
            jwt_key = "aaeb852f-5625-41ff-9e5c-af460edd45e9"
            new_payload = {}
            for key in sorted(payload.keys()):
                if key != "clicks" and not payload[key]:
                    new_payload[key] = "{}"
                else:
                    new_payload[key] = json.dumps(payload[key], separators=(',', '='), ensure_ascii=False)
            pay_loads = urllib.parse.unquote(urlencode(new_payload).replace("+", ""))
            pay_loades = pay_loads.replace('"', '')
            md5_data = pay_loades + "&" + jwt_key
            md = hashlib.md5()
            md.update(md5_data.encode("utf-8"))
            md_result = md.hexdigest()
            logger.info("md5的结果 =" + str(md_result))
            # headers.update({"Authorization": md_result, "Client": client})
            payload.update({"sign": md_result})
        elif i["api_type"] == 4:
            # 国内SDK（生产环境）
            jwt_key = "e4301a29-b4e0-4783-9458-6e1ca9508c2f"
            client = "ewogICJhcHBpZCI6ICI1MjYyMCIsCiAgImlkZmQxIjogIjIwMjIwMTExOmIwZTM2OTEwYWNjZGQ4MzZjNGE2ODI0OGQ0ODUyZGI0IiwKICAiZW11bGF0b3IiOiAiMCIsCiAgIm9wIjogIuS4reWbveenu+WKqCIsCiAgImRldmljZW5hbWUiOiAiaVBob25lOV8xIiwKICAiY2xpZW50aWQiOiAiNEMzMDVBMjgtRERCNi00RkE1LUE2NkItN0UxQTRGREFGMEU3IiwKICAiYnJhbmQiOiAiQXBwbGUiLAogICJhcHB2ZXJzaW9uIjogIjQuNS4yIiwKICAiaWRmZCI6ICIyMDIyMDExMTpiMGUzNjkxMGFjY2RkODM2YzRhNjgyNDhkNDg1MmRiNCIsCiAgInN5c3RlbXZlcnNpb24iOiAiMTMuNiIsCiAgInVhIjogIk1vemlsbGEvNS4wIChpUGhvbmU7IENQVSBpUGhvbmUgT1MgMTNfNiBsaWtlIE1hYyBPUyBYKSBBcHBsZVdlYktpdC82MDUuMS4xNSAoS0hUTUwsIGxpa2UgR2Vja28pIE1vYmlsZS8xNUUxNDgiLAogICJwYWNrYWdlbmFtZSI6ICJjb20uc3N6ei4yMDIxIiwKICAib3MiOiAiMSIsCiAgInVkaWQiOiAiZTE3OGE4ZjA3ZmZkMjY4NjQ5YWQ4MjNjNWU2NWU3NjA4IiwKICAibmV0IjogIjAiLAogICJ3biI6ICIiLAogICJ0aW1lc3RhbXAiOiAiMTY2MzcyMjk4MyIsCiAgInNka3ZlcnNpb24iOiAiMS40LjYuMyIsCiAgImlkZnYiOiAiNTkzRjc1M0MtRkExNy00QjE1LUFGRDgtMzU4RTFGRjlDMUIzIiwKICAiaWRmZDIiOiAiMjAyMTEyMDc6NjQzNWQ0MGUyNDQ4NTNiNzQ2ODYyYzFiNDE4NTExNmQiLAogICJzY3JlZW5zaXplIjogIjY2N3wzNzUiLAogICJpZGZhIjogIjRDMzA1QTI4LUREQjYtNEZBNS1BNjZCLTdFMUE0RkRBRjBFNyIKfQ=="
            md5_data = json.dumps(i["body"]) + client + jwt_key
            md = hashlib.md5()
            md.update(md5_data.encode("utf-8"))
            md_result = md.hexdigest()
            logger.info("md5的结果 =" + str(md_result))
            headers.update({"Authorization": md_result, "Client": client})
        elif i["api_type"] == 6:
            # 星辰谷（生产环境）element ui + python django + mysql
            jwt_key = "252f5af8-0b91-41e9-b0f4-6773cba89fb6"
            client = "eyJhcHBpZCI6NTQxNjAsImFkaWQiOm51bGwsIm9zIjoxLCJjaGFubmVsIjoiZGVmYXVsdCIsInRpbWVzdGFtcCI6IjE2NjM2NjA3MTciLCJwYWNrYWdlbmFtZSI6ImNvbS5qdW5oYWkuc3RhcnNnYW1lYm94IiwiYnJhbmQiOiJBcHBsZSIsImRldmljZW5hbWUiOiJpUGhvbmUgMTQgUHJvIiwic3lzdGVtdmVyc2lvbiI6IjE2LjAiLCJhcHB2ZXJzaW9uIjoiMS4yLjMiLCJzY3JlZW5zaXplIjoiODUyfDM5MyIsIm9wIjoiIiwibmV0IjoxLCJ3biI6IiIsInVhIjoiTW96aWxsYS81LjAgKGlQaG9uZTsgQ1BVIGlQaG9uZSBPUyAxNl8wIGxpa2UgTWFjIE9TIFgpIEFwcGxlV2ViS2l0LzYwNS4xLjE1IChLSFRNTCwgbGlrZSBHZWNrbykgTW9iaWxlLzE1RTE0OCIsImVtdWxhdG9yIjoxLCJjbGllbnRpZCI6IjM1MTRiZTkxMDUxZDY0MzI5YTYyYzBmN2M5YjQzN2Y3IiwiaWRmdiI6IkY1MDdDMjJFLUNBN0ItNDA5Ni04Q0JBLTkxNDFCNUMyRjUyNiIsImlkZmEiOiIwMDAwMDAwMC0wMDAwLTAwMDAtMDAwMC0wMDAwMDAwMDAwMDAiLCJpZGZkIjoiIiwiaWRmZDEiOiIiLCJpZGZkMiI6IiIsImFuZHJvaWRpZCI6bnVsbCwiaW1laSI6IkY1MDdDMjJFLUNBN0ItNDA5Ni04Q0JBLTkxNDFCNUMyRjUyNiIsIm9haWQiOiIiLCJ2YWlkIjoiIiwiYWFpZCI6IiIsInVkaWQiOiI0NGFiZGM5YmNlMDM2OWZjNGU2YTI3YTIzZTY2YjM3MDIiLCJleHRyYSI6IiJ9"
            md5_data = json.dumps(i["body"]) + client + jwt_key
            md = hashlib.md5()
            md.update(md5_data.encode("utf-8"))
            md_result = md.hexdigest()
            logger.info("md5的结果 =" + str(md_result))
            headers.update({"Authorization": md_result, "Client": client})
        elif i["api_type"] == 3:
            # 国内SDK(测试环境-android)
            jwt_key = "a058c845-5f17-4b17-859d-95c8d1e0e7e2"
            client = "ewogICJhcHBpZCI6IDUwNDM2LAogICJvcyI6ICIyIiwKICAic2RrdmVyc2lvbiI6ICIxLjEzLjAuMDgyOSIsCiAgImFkaWQiOiAiMCIsCiAgIm1pZGRsZXdhcmV2ZXJzaW9uIjogIjEuMTMuMC4wODI5IiwKICAiY2xpZW50aWQiOiAiZDYxOWUxZmE3ZWU2ZTBlYWFmMWRiNzg3ODBlYWU0NjciLAogICJ0aW1lc3RhbXAiOiAxNjYyMDk5NTk1LAogICJwYWNrYWdlbmFtZSI6ICJjb20uanVuaGFpLnl6anEiLAogICJicmFuZCI6ICJPUFBPIiwKICAiZGV2aWNlbmFtZSI6ICJPUFBPIENQSDE4MzUiLAogICJzeXN0ZW12ZXJzaW9uIjogIjEwIiwKICAiYXBwdmVyc2lvbiI6IDEsCiAgInNjcmVlbnNpemUiOiAiMTA4MHwyMDY4IiwKICAib3AiOiAiIiwKICAibmV0IjogMSwKICAid24iOiAiIiwKICAidWEiOiAiTW96aWxsYS81LjAgKExpbnV4OyBBbmRyb2lkIDEwOyBDUEgxODM1IEJ1aWxkL1FQMUEuMTkwNzExLjAyMDsgd3YpIEFwcGxlV2ViS2l0LzUzNy4zNiAoS0hUTUwsIGxpa2UgR2Vja28pIFZlcnNpb24vNC4wIENocm9tZS8xMDQuMC41MTEyLjk3IE1vYmlsZSBTYWZhcmkvNTM3LjM2IiwKICAiZW11bGF0b3IiOiAiMCIsCiAgImlkZnYiOiAiIiwKICAiYW5kcm9pZGlkIjogImFhY2RjMjkzZDNlOGQwNzQiLAogICJpbWVpIjogIiIsCiAgIm9haWQiOiAiOEY3RkU4NzA0RkYzNDk5MTlGMTI5NzE1MEQ4NDM2NTlhNDUyMjNmMWUwMjhmN2VkNDYzOTgyYzY1NjdiMjlmYSIsCiAgInZhaWQiOiAiIiwKICAiYWFpZCI6ICJENjQ5MEVCNjczQTc0OUMyOEE4NDM1QTQwODc3QTk5RmZjMzNkZDk1YjAzMzZiYjU2NzRkOGY4NDljNDVlNjUxIiwKICAidWRpZCI6ICI0MWZkMWYwOGZiMmUyN2IyZjRkNmYyNGViZDhjNjdmMDciLAogICJjcHVfbW9kZWwiOiAiIE1UNjc3MVYvVyIsCiAgImNwdV9hbW91bnQiOiAiOCIsCiAgInJvbV9zaXplIjogMTMxMDcyLAogICJyYW1fc2l6ZSI6IDYxNDQsCiAgImV4dHJhIjogIiIKfQ=="
            md5_data = json.dumps(i["body"]) + client + jwt_key
            md = hashlib.md5()
            md.update(md5_data.encode("utf-8"))
            md_result = md.hexdigest()
            logger.info("md5的结果 =" + str(md_result))
            # headers.update({"Client": client})
            headers.update({"Authorization": md_result, "Client": client})
        elif i["api_type"] == 7:
            jwt_key = "aa2b7854-f4bd-46a4-a574-0e22a2fd8b46"
            client = "ewogICJhcHBpZCIgOiAiNTIzMjQiLAogICJpZGZkMSIgOiAiMjAyMjAxMTE6N2ZjNWQ4NzYyZThjNDBmMGMxMTk2YjE0ZDVmZjQ2YTMiLAogICJlbXVsYXRvciIgOiAiMCIsCiAgIm9wIiA6ICLkuK3lm73ogZTpgJoiLAogICJleHRyYSIgOiB7CiAgICAiYXNhX2luZm8iIDogImV3b2dJQ0poWkVsa0lpQTZJREV5TXpRMU5qYzRPVEFzQ2lBZ0ltdGxlWGR2Y21SSlpDSWdPaUF4TWpNeU16SXlNaXdLSUNBaVkyOXVkbVZ5YzJsdmJsUjVjR1VpSURvZ0lrUnZkMjVzYjJGa0lpd0tJQ0FpYjNKblNXUWlJRG9nTVRJek5EVTJOemc1TUN3S0lDQWlZMkZ0Y0dGcFoyNUpaQ0lnT2lBeE1qTTBOVFkzT0Rrd0xBb2dJQ0poWkVkeWIzVndTV1FpSURvZ01USXpORFUyTnpnNU1Dd0tJQ0FpWTI5MWJuUnllVTl5VW1WbmFXOXVJaUE2SUNKVlV5SXNDaUFnSW1GMGRISnBZblYwYVc5dUlpQTZJSFJ5ZFdVS2ZRPT0iCiAgfSwKICAiZGV2aWNlbmFtZSIgOiAiaVBob25lMTFfNiIsCiAgImNsaWVudGlkIiA6ICJBNzg4RDU1My1BQTMzLTRGQjgtQTNDQy1ENzk0M0Y0NTVGNUUiLAogICJicmFuZCIgOiAiQXBwbGUiLAogICJhcHB2ZXJzaW9uIiA6ICIxLjEiLAogICJpZGZkIiA6ICIyMDIyMDExMTo3ZmM1ZDg3NjJlOGM0MGYwYzExOTZiMTRkNWZmNDZhMyIsCiAgInN5c3RlbXZlcnNpb24iIDogIjE1LjUiLAogICJ1YSIgOiAiTW96aWxsYVwvNS4wIChpUGhvbmU7IENQVSBpUGhvbmUgT1MgMTVfNSBsaWtlIE1hYyBPUyBYKSBBcHBsZVdlYktpdFwvNjA1LjEuMTUgKEtIVE1MLCBsaWtlIEdlY2tvKSBNb2JpbGVcLzE1RTE0OCIsCiAgInBhY2thZ2VuYW1lIiA6ICJjb20uaWp1bmhhaS5zZGsuZ2xvYmFsLmlvcy5kZW1vIiwKICAib3MiIDogIjEiLAogICJ1ZGlkIiA6ICI2ZWQ1ZWU2NjE5YmQ0NzUyOTY5YWQ0YzRkNjIzN2EzMDYiLAogICJuZXQiIDogIjAiLAogICJ3biIgOiAiIiwKICAidGltZXN0YW1wIiA6ICIxNjcyMzc5Mzc4IiwKICAic2RrdmVyc2lvbiIgOiAiMS42LjAuMCIsCiAgImlkZnYiIDogIjAwRDQyMEFFLThBMjMtNDI5Ni1BNDA0LTAyNDQ3N0MxREFCNCIsCiAgImlkZmQyIiA6ICIyMDIxMTIwNzplOTBlNDg5NzU1ZDM2NmI3ODlmZjc2YzZmMTMwMzVmMyIsCiAgInNjcmVlbnNpemUiIDogIjg5Nnw0MTQiLAogICJpZGZhIiA6ICJBNzg4RDU1My1BQTMzLTRGQjgtQTNDQy1ENzk0M0Y0NTVGNUUiCn0="
            md5_data = json.dumps(i["body"]) + client + jwt_key
            md = hashlib.md5()
            md.update(md5_data.encode("utf-8"))
            md_result = md.hexdigest()
            logger.info("md5的结果 =" + str(md_result))
            headers.update({"Authorization": md_result, "Client": client})
        elif i["api_type"] == 5:
            # 星辰谷（测试环境）
            jwt_key = "22e012b9-ce1f-4e3d-85ad-b10c802e8fa8"
            client = "eyJhcHBpZCI6NTI3NTIsImFkaWQiOiIwIiwib3MiOjIsImNoYW5uZWwiOiJkZWZhdWx0IiwidGltZXN0YW1wIjoiMTY2NjY4NDU3NCIsInBhY2thZ2VuYW1lIjoiY29tLmp1bmhhaS5zdGFyc2dhbWVib3giLCJicmFuZCI6InNkbTcxMCIsImRldmljZW5hbWUiOiJQQkRNMDAiLCJzeXN0ZW12ZXJzaW9uIjoiMTAiLCJhcHB2ZXJzaW9uIjoiMS4zLjEiLCJzZGt2ZXJzaW9uIjoiMS4wLjAiLCJzY3JlZW5zaXplIjoiNzgwfDM2MCIsIm9wIjoiIiwibmV0IjoxLCJ3biI6IiIsInVhIjoiTW96aWxsYS81LjAgKExpbnV4OyBBbmRyb2lkIDEwOyBQQkRNMDAgQnVpbGQvUUtRMS4xOTA5MTguMDAxOyB3dikgQXBwbGVXZWJLaXQvNTM3LjM2IChLSFRNTCwgbGlrZSBHZWNrbykgVmVyc2lvbi80LjAgQ2hyb21lLzc3LjAuMzg2NS45MiBNb2JpbGUgU2FmYXJpLzUzNy4zNiIsImVtdWxhdG9yIjowLCJjbGllbnRpZCI6ImU5MGQ1NWEwNmRiMWZjNzYyMmQ3YjQwNzI1NWNiNjYzIiwiaWRmdiI6bnVsbCwiaWRmYSI6IiIsImlkZmQiOiIiLCJpZGZkMSI6IiIsImlkZmQyIjoiIiwiYW5kcm9pZGlkIjoiZWFlMmNmNWJlNTI2NjEwOCIsImltZWkiOiJlN2ExYzJmNS1hOGMzLTQzOGQtOGVjNC0wMjhlYTc0NGFkZTYiLCJvYWlkIjoib294eCIsInZhaWQiOiIiLCJhYWlkIjoiIiwidWRpZCI6IjE1NmZmNDM2MGU2YzFhZjA4ZjM1ZWJmNjkxMzhjODk0OSIsImV4dHJhIjoiIn0=="
            md5_data = json.dumps(i["body"]) + client + jwt_key
            md = hashlib.md5()
            md.update(md5_data.encode("utf-8"))
            md_result = md.hexdigest()
            logger.info("md5的结果 =" + str(md_result))
            headers.update({"Authorization": md_result, "Client": client})
        logger.info("请求头=" + str(headers))

        # 请求方法：1：get， 2：post， 3：put， 4：delete
        # 参数类型：1:form-data， 2:Json， 3:x-www-form-urlencoded， 4:None
        # method处理
        # params处理
        p = i["params"]
        params = {}
        if not p:
            for item in p:
                params[item["key"]] = item["value"]
        logger.info("请求参数 =" + json.dumps(params))

        method = str(i['method'])
        body_type = str(i['body_type'])
        payload =i["body"]
        res = None
        # Get
        if method == "1":
            if body_type == "1":
                res = requests.get(req_url, params=params, headers=headers)
                logger.info("响应结果 =" + res.text)
            elif body_type == "2":
                res = requests.get(req_url, json=payload, headers=headers)
                logger.info("响应结果 =" + res.text)
            elif body_type == "3":
                res = requests.get(req_url, data=payload, headers=headers)
                logger.info("响应结果 =" + res.text)
            elif body_type == "4":
                res = requests.get(req_url, data=payload, headers=headers)
                logger.info("响应结果 =" + res.text)

        # Post
        if method == "2":
            if body_type == "1":
                res = requests.post(req_url, data=payload, headers=headers)
                logger.info("响应结果 =" + res.text)
            elif body_type == "2":
                res = requests.post(req_url, json=payload, headers=headers)
                logger.info("响应结果 =" + res.text)
            elif body_type == "3":
                res = requests.post(req_url, data=payload, headers=headers)
                logger.info("响应结果 =" + res.text)
            elif body_type == "4":
                res = requests.post(req_url, data=payload, headers=headers)
                logger.info("响应结果 =" + res.text)
        # Put
        if method == "3":
            if body_type == "1":
                res = requests.put(req_url, data=payload, headers=headers)
                logger.info("响应结果 =" + res.text)
            elif body_type == "2":
                res = requests.put(req_url, json=payload, headers=headers)
                logger.info("响应结果 =" + res.text)
            elif body_type == "3":
                res = requests.put(req_url, data=payload, headers=headers)
                logger.info("响应结果 =" + res.text)
            elif body_type == "4":
                res = requests.post(req_url, data=payload, headers=headers)
                logger.info("响应结果 =" + res.text)

        # Delete
        if method == "4":
            if body_type == "1":
                res = requests.delete(req_url, data=payload, headers=headers)
                logger.info("响应结果 =" + res.text)
            elif body_type == "2":
                res = requests.delete(req_url, json=payload, headers=headers)
                logger.info("响应结果 =" + res.text)
            elif body_type == "3":
                res = requests.delete(req_url, data=payload, headers=headers)
                logger.info("响应结果 =" + res.text)
            elif body_type == "4":
                res = requests.delete(req_url, data=payload, headers=headers)
                logger.info("响应结果 =" + res.text)
        if res is None or res == "":
            assert_res = res.text
        else:
            assert_res = json.loads(res.text)
            # assert处理
            assert_result = []
            assert_a = i["assert"]
            assert_data = {}
            result = []
            if assert_a != "":
                for item in assert_a:
                    assert_data[item['assert_key']] = item['assert_value']
                    if assert_data[item['assert_key']] == '' or assert_data[item['assert_key']] is None:
                        assert_result.extend(result)
                    else:
                        for key in assert_data.keys():
                            if key in assert_res.keys():
                                if str(assert_data[key]) == str(assert_res[key]):
                                    assert_status = {
                                        "status": True,
                                        "assert_key": key,
                                        "assert_value": assert_data[key]
                                    }
                                else:
                                    assert_status = {
                                        "status": False,
                                        "assert_key": key,
                                        "assert_value": str(assert_data[key])
                                    }
                            else:
                                assert_status = {
                                    "status": False,
                                    "assert_key": key,
                                    "assert_value": str(assert_data[key])
                                }
                        result.append(assert_status)
            assert_result.extend(result)
            logger.info("断言结果=" + str(assert_result))
        if assert_result:
            for a in assert_result:
                if a["status"]:
                    a_status = 1
                else:
                    a_status = 0
        else:
            a_status = 1
        p = Parametric_result.objects.create(url=req_url, body=payload, response=res.text, params=params,
                                             assert_data=assert_result, status=a_status,
                                             p_user_id=user_id, method=int(method),
                                             p_testcase_id=t_id, response_time=str(res.elapsed.total_seconds()))
        p_result = {
            "url": req_url,
            "body": payload,
            "response": json.loads(res.text),
            "method": int(method),
            "params": params,
            "assert_data": assert_result,
            "status": p.status,
            "username": p.p_user.username,
            "testcase_id": t_id,
            "id": p.id,
            "response_time": str(res.elapsed.total_seconds()) + '秒',
        }
        p_list.append(p_result)
    return JsonResponse({
        "code": 200,
        "message": "批量执行成功",
        "content": p_list
    })


def get_batch_result(request):
    try:
        data = json.loads(request.body)
        id = data["testcase_id"]
        pr = Parametric_result.objects.filter(p_testcase_id=id)
        size_page = data["size_page"]
        current_pages = data["current_page"]
        parametric_total = len(pr)
        result = []
        for p in pr:
            p_result = {
                "id": p.id,
                "url": p.url,
                "body": p.body,
                "response": json.loads(p.response),
                "method": p.method,
                "params": p.params,
                "assert_data": p.assert_data,
                "headers": p.p_testcase.t_header,
                "username": p.p_user.username,
                "testcase_id": p.p_testcase_id,
                "response_time": p.response_time + '秒',
                "status": p.status
            }
            result.append(p_result)
        p = Paginator(result, size_page)
        page1 = p.page(current_pages)
        parametric_list = page1.object_list
        return JsonResponse({
            "code": 200,
            "content": parametric_list,
            "parametric_total": parametric_total,
            "size_page": size_page,
            "current_page": current_pages
        })
    except Exception as e:
        return JsonResponse({
            "code": 100,
            "message": str(e)
        })


def get_single_batch_result(request):
    try:
        data = json.loads(request.body)
        id = data["id"]
        pr = Parametric_result.objects.filter(id=id)
        result = []
        for p in pr:
            p_result = {
                "id": p.id,
                "url": p.url,
                "body": json.loads(p.body.replace("'", '"')),
                "response": json.loads(p.response),
                "method": p.method,
                "params": json.loads(p.params.replace("'", '"')),
                "assert_data": {"assert": eval(p.assert_data)},
                "headers": eval(p.p_testcase.t_header),
                "username": p.p_user.username,
                "testcase_id": p.p_testcase_id,
                "response_time": p.response_time + '秒',
                "status": p.status
            }
            result.append(p_result)
        return JsonResponse({
            "code": 200,
            "message": "获取结果成功",
            "content": result,
        })
    except Exception as e:
        return JsonResponse({
            "code": 100,
            "message": str(e)
        })
